package com.bxs.demo;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class SocketDemo2 {
    static class Server{
        ServerSocket serverSocket;
        public Server() throws IOException {
            serverSocket = new ServerSocket(9999);
            //监听
            Socket socket = null;
            while((socket = serverSocket.accept()) != null){
                InputStream inputStream = socket.getInputStream();
                OutputStream outputStream = socket.getOutputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuffer sb = new StringBuffer();
                char buf[] = new char[1024];
                int len = 0;
                sb.append(bufferedReader.read(buf, 0, 1024));
                System.out.println("server receive: " + sb);
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream));
                bw.write("server response");
                bw.close();
                bufferedReader.close();
                outputStream.close();
                inputStream.close();
            }
        }
    }

    static class Client{
        public void send() throws IOException {
            Socket socket = new Socket("127.0.0.1", 9999);
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write("client msg".getBytes(StandardCharsets.UTF_8));
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            char buf[] = new char[1024];
            int len = 0;
            StringBuffer sb = new StringBuffer();
            do{
                len = bufferedReader.read(buf, 0, 1024);
                sb.append(buf, 0, len);
            }while (bufferedReader.ready());
            System.out.println("read: " + sb.toString());
        }
    }

    public static void main(String[] args) throws IOException {
        SocketDemo.Server server = new SocketDemo.Server();
        SocketDemo.Client client = new SocketDemo.Client();
        client.send();
    }
}
